package com.springbootcrud.user.controller;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.springbootcrud.email.EmailHelper;
import com.springbootcrud.email.EmailMessage;
import com.springbootcrud.email.EmailMessageAttachment;
import com.springbootcrud.user.entity.Index;
import com.springbootcrud.user.entity.LockTables;
import com.springbootcrud.user.entity.Space;
import org.apache.commons.io.FileUtils;
import com.springbootcrud.user.entity.LogEntry;
import com.springbootcrud.user.service.MonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("Monitor")
public class MonitorController {
    @Autowired
    MonitorService monitorService;

    @ResponseBody
    @RequestMapping("/getAll")
    public List<LogEntry> getAll() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String yesterday = sdf.format(cal.getTime());

        ArrayList<String> list = new ArrayList<>();
        ArrayList<String> filelist = new ArrayList<>();
        list.add("D:\\tzjd\\monitorreport\\sofa_home\\logs\\errors\\error.log");
        list.add("D:\\tzjd\\monitorreport\\sofa_home\\logs\\errors\\errors.log");
        list.add("D:\\tzjd\\monitorreport\\sofa_home\\logs\\errors\\err." + yesterday + ".0.log");
        list.add("D:\\tzjd\\monitoring\\sofa_home\\logs\\errors\\err." + yesterday + ".0.log");
        for (int i = 0; i < list.size(); i++) {
            File file = new File(list.get(i));
            if (file.exists()) {
                filelist.add(list.get(i));
            }
        }
        System.out.println(filelist);
        List<LogEntry> entrie =null;
        List<LogEntry> entries = null;
        if (filelist != null && !filelist.isEmpty()) {
            for (int i = 0; i < filelist.size(); i++) {
                String log = null;
                try {
                    log = FileUtils.readFileToString(new File(filelist.get(i)), "GBK");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String[] parts = filelist.get(i).split("\\\\");  // 按 \ 分割
                String path = parts[2];
                entrie = monitorService.parseLog(log, path);
                if (entries != null) {
                      entries.addAll(entrie);
                } else {
                    entries = entrie;
                }




            }
            return entries;
        }

        return entries;
    }

    @ResponseBody
    @RequestMapping("/insert")
    public void insert() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String yesterday = sdf.format(cal.getTime());
        ArrayList<String> list = new ArrayList<>();
        ArrayList<String> filelist = new ArrayList<>();
        list.add("D:\\tzjd\\monitorreport\\sofa_home\\logs\\errors\\error.log");
        list.add("D:\\tzjd\\monitorreport\\sofa_home\\logs\\errors\\errors.log");
        list.add("C:\\logs\\errors\\errorss" + yesterday + ".log");
        list.add("D:\\tzjd\\monitorreport\\sofa_home\\logs\\errors\\err." + yesterday + ".0.log");
        for (int i = 0; i < list.size(); i++) {
            File file = new File(list.get(i));
            if (file.exists()) {
                filelist.add(list.get(i));
            }
        }
        if (filelist != null && !filelist.isEmpty()) {
            for (int i = 0; i < filelist.size(); i++) {
                String log = null;
                try {
                    log = FileUtils.readFileToString(new File(filelist.get(i)), "GBK");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String[] parts = filelist.get(i).split("\\\\");  // 按 \ 分割
                String path = parts[2];
                List<LogEntry> entries = monitorService.parseLog(log, path);
                // 打印提取的关键信息
                for (LogEntry entry : entries) {
                    monitorService.save(entry);
                }

            }
        }

    }


    @ResponseBody
    @RequestMapping("/getSpaceAll")
    public List<Space> getSpaceAll() {

        return monitorService.getSpaceAll();
    }

    @ResponseBody
    @RequestMapping("/getLockAll")
    public List<LockTables> getLockAll() {

        return monitorService.getLockAll();
    }

    @ResponseBody
    @RequestMapping("/getIndexAll")
    public List<Index> getIndexAll() {

        return monitorService.getIndexAll();
    }

    @ResponseBody
    @RequestMapping("/downLoad")
    public void downLoad() throws IOException {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String yesterday = sdf.format(cal.getTime());
        WebClient webClient = new WebClient();
// 启用JS支持(关键!)
        webClient.getOptions().setJavaScriptEnabled(true);
        webClient.getOptions().setCssEnabled(false); // 可禁用CSS加速

        try {
            HtmlPage page = webClient.getPage("http://localhost:8080/monitorIndex.html");

            // 等待JS执行完成
            webClient.waitForBackgroundJavaScript(5000); // 5秒等待

            String savePath = "D:\\Download\\投资合规巡检报告" + yesterday + ".html";
            // 获取完整HTML
            String completeHtml = page.asXml();

            try (OutputStreamWriter writer = new OutputStreamWriter(
                    new FileOutputStream(savePath), StandardCharsets.UTF_8)) {
                writer.write(completeHtml);

//            try (FileWriter writer = new FileWriter(savePath)) {
//                writer.write(completeHtml);
//                System.out.println("HTML文件已成功保存到: " + savePath);
            } catch (IOException e) {
                System.err.println("保存文件时出错: " + e.getMessage());
            }
        } finally {
            webClient.close();
        }

    }

    @ResponseBody
    @RequestMapping("/send")
    public void send() throws Exception {
        EmailHelper.init("email.xml");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String yesterday = sdf.format(cal.getTime());

        System.out.println(this.getClass().getResource("/"));
        EmailMessage emailMessage = new EmailMessage();
        emailMessage.setSubject("投资合规巡检报告");
        List<String> to = new ArrayList<String>();
        to.add("yss_tzjd@cssfintra.com");
        emailMessage.setTo(to);
        emailMessage.setMsg("投资合规巡检报告");
        EmailMessageAttachment attachment = new EmailMessageAttachment();
        //附件描述
        attachment.setDescription("投资合规巡检报告");
        //附件名称
        attachment.setName("投资合规巡检报告" + yesterday + ".html");
        //附件路径
        attachment.setPath("D:\\Download\\投资合规巡检报告" + yesterday + ".html");
        emailMessage.addAttachment(attachment);
        EmailHelper.send(emailMessage);

    }


}
